package clas.ac.cn.common.webfilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.util.*;

/**
 * 功能：Request包装类，用来实现对拦截器对Request 输入流的多次读写不影响@RequestBody的注解使用
 * 
 * 版本:1.0
 * 
 * 开发者:张邹
 * 
 * 开发地点：四川成都科分院文献情报中心信息技术部
 * 
 * 开发(最近修改)时间：2019年6月4日上午11:47:09
 */
public class RequestWrapper extends HttpServletRequestWrapper {



	private final Map<String, String> customHeaders;

	public RequestWrapper(HttpServletRequest request){
		super(request);
		this.customHeaders = new HashMap<String, String>();
	}

	public void putHeader(String name, String value){
		this.customHeaders.put(name, value);
	}

	@Override
	public String getHeader(String name) {
		// check the custom headers first
		String headerValue = customHeaders.get(name);

		if (headerValue != null){
			return headerValue;
		}
		// else return from into the original wrapped object
		return ((HttpServletRequest) getRequest()).getHeader(name);
	}

	@Override
	public Enumeration<String> getHeaderNames() {
		// create a set of the custom header names
		Set<String> set = new HashSet<String>(customHeaders.keySet());

		// now add the headers from the wrapped request object
		@SuppressWarnings("unchecked")
		Enumeration<String> e = ((HttpServletRequest) getRequest()).getHeaderNames();
		while (e.hasMoreElements()) {
			// add the names of the request headers into the list
			String n = e.nextElement();
			set.add(n);
		}

		// create an enumeration from the set and return
		return Collections.enumeration(set);
	}

}
